package xyz.shu.service;

import com.google.common.base.Preconditions;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.shu.dao.SysDeptMapper;
import xyz.shu.exception.ParamException;
import xyz.shu.model.SysDept;
import xyz.shu.param.DeptParam;
import xyz.shu.util.BeanValidator;
import xyz.shu.util.LevelUtil;

import java.util.Date;
import java.util.List;

@Service
public class SysDeptService {
    @Autowired
    private SysDeptMapper sysDeptMapper;

    public void save(DeptParam deptParam){
        BeanValidator.check(deptParam);

        if (checkExist(deptParam.getParentId(),deptParam.getName(),deptParam.getId())){
            throw  new ParamException("同一层级下存在相同名称的部门");
        }

        SysDept dept = SysDept.builder().name(deptParam.getName())
                .parentId(deptParam.getParentId()).seq(deptParam.getSeq())
                .remark(deptParam.getRemark()).build();

        dept.setLevel(LevelUtil.calculateLevel(getLevel(deptParam.getParentId()),deptParam.getParentId()));
        dept.setOperator("system");
        dept.setOperateIp("127.0.0.1");
        dept.setOperateTime(new Date());

        sysDeptMapper.insertSelective(dept);


    }

    public void update(DeptParam deptParam){
        BeanValidator.check(deptParam);

        if (checkExist(deptParam.getParentId(),deptParam.getName(),deptParam.getId())){
            throw  new ParamException("同一层级下存在相同名称的部门");
        }
        SysDept before=sysDeptMapper.selectByPrimaryKey(deptParam.getId());

        Preconditions.checkNotNull(before,"待更新的部门不存在");

        SysDept after = SysDept.builder().id(deptParam.getId()).name(deptParam.getName())
                .parentId(deptParam.getParentId()).seq(deptParam.getSeq())
                .remark(deptParam.getRemark()).build();
        after.setLevel(LevelUtil.calculateLevel(getLevel(deptParam.getParentId()),deptParam.getParentId()));
        after.setOperator("system-update");
        after.setOperateIp("127.0.0.1");
        after.setOperateTime(new Date());
        this.updateWithChild(before,after);
    }

    @Transactional(rollbackFor = Exception.class)
    void updateWithChild(SysDept before,SysDept after){

        String newLevelPreFix=after.getLevel();
        String oldLevelPrefix=before.getLevel();
        if (!after.getLevel().equals(before.getLevel())){
            List<SysDept> deptList= sysDeptMapper.getChildDeptByLevel(before.getLevel());
            if (CollectionUtils.isNotEmpty(deptList)){
                for(SysDept dept:deptList){
                    String level=dept.getLevel();
                    if (level.indexOf(oldLevelPrefix)==0){
                        level = newLevelPreFix+level.substring(oldLevelPrefix.length());
                        dept.setLevel(level);
                    }
                }
                sysDeptMapper.batchUpdateLevel(deptList);
            }
        }
        sysDeptMapper.updateByPrimaryKey(after);
    }

    private  boolean checkExist(Integer parentId,String deptName,Integer deptId){
        return sysDeptMapper.countByNameAndParentId(parentId,deptName,deptId)>0;
    }


    private String getLevel(Integer deptId){
        SysDept dept = sysDeptMapper.selectByPrimaryKey(deptId);
        if (dept==null){
            return null;
        }
        return dept.getLevel();
    }
}
